package com.lijun.SpringBootJavaFX.controller.person;

import com.lijun.SpringBootJavaFX.config.MainWindowHandler;
import com.lijun.SpringBootJavaFX.config.javaFxView.PersonView;
import com.lijun.SpringBootJavaFX.model.person.People;
import com.lijun.SpringBootJavaFX.model.system.SystemCode;
import com.lijun.SpringBootJavaFX.service.person.PersonService;
import com.lijun.SpringBootJavaFX.service.system.SystemCodeService;
import com.lijun.SpringBootJavaFX.utils.DateUtil;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.stage.*;
import javafx.util.StringConverter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.util.*;

@FXMLController
public class PeopleController implements Initializable {


    @FXML
    private TextField personName;
    @FXML
    private ToggleGroup gender;
    @FXML
    private DatePicker birthday;
    @FXML
    private FlowPane insterestPanel;
    @FXML
    private ComboBox eduCombo;

    private CheckBox[] interestCheckBoxs;

    //人员编辑窗口
    Stage personEditWindow;

    @FXML
    private TextField chooseFilePath;

    @FXML
    private TextArea detail;

//    @FXML
//    private ToggleGroup gender;
//    @FXML
//    private DatePicker birthday;

//    private PersonVo person = new PersonVo();

    @Autowired
    PersonService personService;

    @Autowired
    SystemCodeService systemCodeService;

    public PeopleController() {
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
//        personName.textProperty().bindBidirectional(person.nameProperty());
//        personName.textProperty().bindBidirectional(person.detailProperty());
        //radio添加改变选项的监听器
//        gender.selectedToggleProperty().addListener(
//            (ObservableValue<? extends Toggle> ov, Toggle old_Toggle,
//             Toggle new_Toggle) -> {
//                if (gender.getSelectedToggle() != null) {
//                    person.setGenderValue(Integer.parseInt((String) gender.getSelectedToggle().getUserData()));
//                    person.setGenderName(((RadioButton) gender.getSelectedToggle()).getText());
//                }
//            }
//        );

        //动态获取兴趣码表数据并作为兴趣复选选项
        List<SystemCode> interestList = systemCodeService.getSysteCodeListByCodeType("INTEREST");
        interestCheckBoxs = new CheckBox[interestList.size()];
        for (int i = 0; i < interestList.size(); i++) {
            CheckBox cb = new CheckBox();
            SystemCode code = interestList.get(i);
            cb.setText(code.getName());
            cb.setUserData(code.getCode());
            interestCheckBoxs[i] = cb;
            insterestPanel.getChildren().add(cb);
        }


        List<SystemCode> eduList = systemCodeService.getSysteCodeListByCodeType("EDU");
        for (SystemCode eduCodeNode : eduList) {
            Map<String, String > eduComboOption = new HashMap<>();
            eduComboOption.put("name",eduCodeNode.getName());
            eduComboOption.put("code",eduCodeNode.getCode());
            eduCombo.getItems().add(eduComboOption);
        }

        eduCombo.valueProperty().addListener((obs, oldVal, newVal) -> {
                    if (newVal != null) {
                    }
                }
        );

        //下拉框创建转换器，使其能够将name当作选项显示
        eduCombo.setConverter(new StringConverter<Map<String, String> >() {
            @Override
            public String toString(Map<String, String> object) {
                return object.get("name");
            }

            @Override
            public Map<String, String>  fromString(String string) {
                return null;
            }
        });

//        ObservableList<String> options =
//                FXCollections.observableArrayList(
//                        "Option 1",
//                        "Option 2",
//                        "Option 3"
//                );
//        eduCombo.setEditable(true);
//        eduCombo.setItems(options);
//        eat.selectedProperty().bindBidirectional(person.eatProperty());
//        drink.selectedProperty().bindBidirectional(person.drinkProperty());
//        play.selectedProperty().bindBidirectional(person.playProperty());
//        happy.selectedProperty().bindBidirectional(person.happyProperty());
        /*eat.selectedProperty().addListener(new ChangeListener<Boolean>() {
            public void changed(ObservableValue<? extends Boolean> ov,
                                Boolean old_val, Boolean new_val) {
                System.out.println(eat.isSelected());
            }
        });*/


    }


    @Value("${app.uploadPath}")
    String uploadPath;

    @FXML
    public void savePerson(final Event event){
        People people = new People();
        //TODO 表单校验（包括必填项、格式、长度等）
        //TODO 处理name及code值
        String interestNames="";
        String interestCodes="";
        for (CheckBox interestCheckBox : interestCheckBoxs) {
            if (interestCheckBox.isSelected()) {
                interestNames += interestCheckBox.getText()+",";
                interestCodes += interestCheckBox.getUserData()+",";
            }
        }
        //兴趣
        people.setInterestCodes(interestCodes);
        people.setInterestNames(interestNames);
//        姓名
        people.setName(personName.getText());
//        描述
        people.setDetail(detail.getText());
//        性别
        if (gender.getSelectedToggle() != null) {
            people.setGenderName(((RadioButton) gender.getSelectedToggle()).getText());
            people.setGenderValue((String) gender.getSelectedToggle().getUserData());
        }
//        生日
        if (birthday.getValue() != null) {
            people.setBirthday(new Date(birthday.getValue().toEpochDay()));
        }
//        学历
        SystemCode eduCodeNode = (SystemCode) eduCombo.getSelectionModel().getSelectedItem();
        if(eduCodeNode!=null){
            people.setEduCode(eduCodeNode.getCode());
            people.setEduName(eduCodeNode.getName());
        }
        personService.savePerson(people);
        if(StringUtils.isNotBlank(chooseFilePath.getText())){
            //文件上传
            File file = new File(chooseFilePath.getText());
            if(file.exists()){
                String fileName = StringUtils.substringAfterLast(chooseFilePath.getText(),File.separator);
                File outDir = new File(uploadPath+"/"+new Date().getTime()+"/");
                if(!outDir.exists()){
                    outDir.mkdirs();
                }
                File outFile = new File(outDir.getPath() + "/" + fileName);
                if(!outFile.exists()){
                    try {
                        outFile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    FileCopyUtils.copy(file,outFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText("警告");
                alert.setContentText("文件不存在,路径："+chooseFilePath.getText());
                alert.showAndWait();
                return;
            }
        }
        //保存完关闭窗口
        ((Stage)((Button)event.getSource()).getScene().getWindow()).close();
    }

    public void chooseFile(){
        FileChooser.ExtensionFilter[] extensionFilter = null;
        File file = null;
        //创建文件选择器
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("请选择文件");
        fileChooser.setInitialDirectory(FileSystemView.getFileSystemView().getHomeDirectory());
        if (extensionFilter != null) {
            fileChooser.getExtensionFilters().addAll(extensionFilter);
        }
        file = fileChooser.showOpenDialog((Window)null);
        chooseFilePath.setText(file.getPath());
    }

    public void closeWindow(MouseEvent event){
        ((Stage)((Label)event.getSource()).getScene().getWindow()).close();
    }

    /**
     * 清空表单
     */
    public void clearForm(){
        System.out.println("清空表单");
        personName.clear();
        for (Toggle toggle : gender.getToggles()) {
            toggle.setSelected(false);
        }
//        birthday.getEditor().clear();
        birthday.setValue(null);
        detail.clear();
        chooseFilePath.clear();
        eduCombo.setValue(null);
        for (CheckBox interestCheckBox : interestCheckBoxs) {
            interestCheckBox.setSelected(false);
        }
    }

    /**
     * person窗口视图
     * 使用此方式注入视图，在该视图对应的controller中才可以使用@Autowired注入
     */
    @Autowired
    PersonView personView;

    String personId;

    public void openWindow(ActionEvent actionEvent, String id){
        personId = id;
        if (personEditWindow == null) {
            personEditWindow = new Stage();
            //窗口关闭改为隐藏
            personEditWindow.setOnCloseRequest((windowEvent)-> {
                personEditWindow.hide();
            });
            personEditWindow.setOnHidden((windowEvent)->{
                clearForm();
            });
            personEditWindow.setOnShown((windowEvent)->{
                //窗体打开时判断是否需要回显数据
                loadPersonDataToView(personId);
            });
            //此种方式加载视图无法使用spring的@Autowired
//        URL url = getClass().getResource("/fxml/personEdit.fxml");
//        ScrollPane root = FXMLLoader.load(url);
            Scene secondScene = new Scene(personView.getView());
            personEditWindow.setScene(secondScene);
            personEditWindow.setTitle("登记窗口");
//        secondStage.setAlwaysOnTop(true);
//        secondStage.setMaximized(true);
            //窗口模态(在应用内模态)
            personEditWindow.initModality(Modality.WINDOW_MODAL);
            personEditWindow.initStyle(StageStyle.TRANSPARENT);
            personEditWindow.initOwner(MainWindowHandler.getMainWindow());
        }
        personEditWindow.show();
    }

    private void loadPersonDataToView(String id){
        if (StringUtils.isNotBlank(personId)) {
            try {
                People people = personService.loadPerson(id);
                String interestCodes = people.getInterestCodes();
                //回显兴趣
                if(StringUtils.isNotBlank(interestCodes)){
                    String[] interestCodesArr = interestCodes.split(",");
                    List<String> list = Arrays.asList(interestCodesArr);
                    for (CheckBox interestCheckBox : interestCheckBoxs) {
                        if (list.contains(interestCheckBox.getUserData())) {
                            interestCheckBox.setSelected(true);
                        }

                    }
                }
                //姓名回显
                personName.setText(people.getName());
                //性别回显
                for (Toggle toggle : gender.getToggles()) {
                    if (toggle.getUserData().equals(people.getGenderValue())) {
                        toggle.setSelected(true);
                    }
                }
                //学历回显
                Map<String, String > eduMap = new HashMap<>();
                eduMap.put("name", people.getEduName());
                eduMap.put("code", people.getEduCode());
                eduCombo.setValue(eduMap);
//                eduCombo.setPromptText(eduCombo.getConverter().toString(eduCombo.getValue()));
                //生日回显
                birthday.setValue( DateUtil.date2LocalDate(people.getBirthday()));
                //描述回显
                detail.setText(people.getDetail());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

}
